package com.sduept.nwld.mobile.rest;

import com.sduept.nwld.mobile.manager.MobileUserInfoManager;
import com.sduept.nwld.mobile.manager.MobileUtil;
import com.sduept.permission.entity.FunctionEntityBean;
import com.sduept.permission.entity.PersonnelEntityBean;
import com.sduept.permission.enums.FunctionTypeEnum;
import com.sduept.permission.manager.FunctionManager;
import com.sduept.permission.manager.PersonnelManager;
import com.sduept.utils.MD5;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.inject.Inject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/mobileMenu")
public class MobileMenuService {
	@Autowired
	private MobileUserInfoManager mu;
	@Autowired
	private PersonnelManager pm;
	@Inject
	private FunctionManager fm;
	//SQL注入检测类
	@Inject
	private MobileUtil mobileUtil;
	
	/**
	 * 根据4A账号获取该账户所有有权限的app菜单，并和app现有的菜单进行对比
	 * @param account
	 * @param currentFun app现有菜单   1.没有找到对应的web账户或者没有权限返回空串。2.菜单没有改变返回'[]'
	 * @return
	 */

    @GetMapping("/getMenuByAccount/{account}/{currentFun}")
	public String getMenuByAccount(@PathVariable("account") String account,@PathVariable("currentFun") String currentFun){
		try {
			account = mobileUtil.SQLInjectCheck(account);
			currentFun = mobileUtil.SQLInjectCheck(currentFun);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		String result = "";
		PersonnelEntityBean person = pm.findPersonnelByCode(account);
		//PersonnelConfigure person=mu.findUserByAccount(account);
		if(null!=person) {
			List<FunctionEntityBean> functionList=fm.findPersonAuthcFunction(person.getCode(), FunctionTypeEnum.approot);
			if(functionList.size()>0) {
				//有权限
				String functionStr = JSONArray.fromObject(functionList).toString();
				String functionMd5 = null;
				try {
					functionMd5 = MD5.md5(URLEncoder.encode(functionStr, "utf-8"));//和前台对应，先编码后再md5
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				if(currentFun.equals(functionMd5)){
					result = "[]";//无改变
				}else{
					result = functionStr;
				}
			}
		}else {
			log.info(account+"APP用户不存在");
		}
		return result;
	}
}
